<template>
  <div ref="workbench">
    <ContentWrap>
      <div class="inner-container">
        <div v-for="(form, index) in FieldForm.fields" :key="index" class="form-options">
          <!--TODO: 先丑陋的这么写吧！！ -->
          <div
            v-if="index == 9"
            class="float-left h-30px w-120px text-[var(--secondary-text-color)]"
            ><el-link><span class="text-12px">更多条件</span> </el-link></div
          >
          <div class="mb-10px flex items-center" v-if="form.formType != 'select'">
            <div class="w-120px text-12px text-[var(--secondary-text-color)]">
              {{ form.label }}
            </div>
            <!-- TODO: 先按照if条件的形式往下写，最后封装成field组件 -->
            <div v-if="form.formType == 'checkbox'" class="w-1020px">
              <el-checkbox-group v-model="form.value">
                <el-checkbox
                  size="small"
                  class="w-100px"
                  v-for="(option, oi) in form.options"
                  :key="oi"
                  :label="option.value"
                  >{{ option.label }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <div v-else-if="form.formType == 'radio'" class="w-1020px">
              <el-radio-group v-model="form.value">
                <el-radio
                  size="small"
                  class="w-100px"
                  v-for="(option, oi) in form.options"
                  :key="oi"
                  :label="option.value"
                  >{{ option.label }}</el-radio
                >
              </el-radio-group>
            </div>

            <div v-else-if="form.formType == 'text'" class="w-1020px">
              <el-input v-model="form.value" placeholder="输入关键字查询">
                <template #prepend>
                  <el-select v-model="form.field" placeholder="Select" style="width: 115px">
                    <el-option
                      v-for="(option, oi) in form.options"
                      :label="option.label"
                      :key="oi"
                      :value="option.value"
                    />
                  </el-select>
                </template>
              </el-input>
            </div>
            <div v-if="form.field == 'area'" class="w-1020px">
              <el-cascader
                clearable
                class="w-1020px"
                v-model="form.value"
                :options="areaOptions"
                :props="{
                  label: 'name',
                  value: 'code',
                  emitPath: false,
                  checkStrictly: true,
                  multiple: true
                }"
              />
            </div>
            <div v-if="form.field == 'industry'" class="w-1020px">
              <el-cascader
                clearable
                class="w-1020px"
                v-model="form.value"
                :options="industryOptions"
                :props="{
                  label: 'name',
                  value: 'name',
                  emitPath: false,
                  checkStrictly: true,
                  multiple: true
                }"
              />
            </div>
          </div>
          <div class="more-option float-left" v-else>
            <div class="w-120px">
              <!-- TODO: 这个下拉选择器先放着， UI和交互有时间在做！！！补充：使用radio吧，然后修改样式 -->
              <el-popover placement="top" trigger="click">
                <template #reference>
                  <el-link :type="form.value != '' ? 'primary' : ''"
                    ><span class="text-12px">{{ form.label }}</span>
                    <Icon
                      v-if="form.value != ''"
                      @click="form.value = ''"
                      icon="ep:close"
                      class="ml-5px"
                    />
                  </el-link>
                </template>
                <div class="radio-select-group">
                  <el-radio-group v-model="form.value">
                    <el-radio
                      v-for="(option, oi) in form.options"
                      :key="oi"
                      :label="option.value"
                      >{{ option.label }}</el-radio
                    >
                  </el-radio-group>
                </div>
              </el-popover>
            </div>
          </div>
        </div>
        <!-- 用于清除浮动，以及占位 -->
        <div class="clear-both h-10px"></div>
        <div class="form-options flex justify-end w-1140px items-center">
          <el-tooltip content="选择条件后请点击搜索" placement="bottom" effect="light">
            <el-icon size="16" color="#e6a23c"><InfoFilled /></el-icon>
          </el-tooltip>
          <el-button @click="reset" class="ml-10px">重置</el-button>
          <el-button type="primary" :icon="Search" @click="searchFn">搜索</el-button>
        </div>
      </div>
    </ContentWrap>

    <ContentWrap>
      <div class="inner-container" v-loading="loading">
        <div class="form-title flex justify-between">
          <el-text> 搜索结果 </el-text>
          <el-button type="primary" :icon="Unlock" @click="onClickUnlock">批量领取</el-button>
        </div>
        <div class="page-box">
          <CompanyList
            :list="dataList.results"
            @refresh-val="refreshData"
            @show-item="onEntNameClick"
          />
        </div>
        <Pagination
          :total="dataList.total"
          :page="queryParam.pageNo"
          :limit="queryParam.pageSize"
          @pagination="doSearch"
        />
      </div>
    </ContentWrap>
    <!-- 企业详情 -->
    <EnterpriseDetails ref="companyDetail" @refresh-val="detailRefreList" />
  </div>
  <TableSelect
    :modelValue="selectedItems"
    ref="tableSelect"
    @update:model-value="receiveCompany"
    @get-table-fun="getTableFun"
  >
    <el-table-column prop="companyInfo.companyName" label="企业名称" align="center" />
    <el-table-column prop="companyInfo.numberCount" label="联系电话(条)" align="center" />
    <el-table-column label="解锁状态" align="center">
      <template #default="scope">
        <el-tag type="info" v-if="scope.row.companyInfo.received"
          >已被{{ scope.row.companyInfo.receiveUser }}领取</el-tag
        >
        <el-tag type="primary" v-else>待领取</el-tag>
      </template>
    </el-table-column>
  </TableSelect>
</template>
<!-- TODO: 1.更多条件的css对齐调整，更多条件的下拉选择器交互开发 -->
<!-- TODO: 2.已选条件的展示和开发，以及删除已选条件的form表单响应式开发 -->
<!-- TODO: 3.领取企业功能， 企业详情对接开发 -->

<script setup>
import EnterpriseDetails from '../components/EnterpriseDetaill/index.vue'
import * as advanceApi from '@/api/ent/advanceSearch/index'
import CompanyList from '../advanceSearch/CompanyList.vue'
import * as LocalApi from '@/api/ent/company/local'
import * as CompanyApi from '@/api/ent/company'
import { useEntStore } from '@/store/modules/ent'
import { isArray } from '@/utils/is'
import { Unlock, Search, InfoFilled } from '@element-plus/icons-vue'

const route = useRoute()
const companyDetail = ref(null)

// 查询状态
const loading = ref(false)

// 查询参数
const queryParam = ref({
  pageNo: 1,
  pageSize: 15,
  operations: [
    {
      condition: 'must',
      queryFields: []
    }
  ]
})
const tableSelect = ref(null)
const selectedItems = ref([])

//显示弹窗
const onClickUnlock = () => {
  tableSelect.value.openDialogVisible({
    value: dataList.results,
    totals: dataList.total,
    pageNo: queryParam.value.pageNo,
    pageSize: queryParam.value.pageSize
  })
}
// 批量解锁
const receiveCompany = async (val) => {
  let ids = []
  if (val.length) {
    val.forEach((item) => {
      ids.push(item.companyInfo.cid)
    })
    const res = await advanceApi.companyReceive({ ids })
    if (res) ElMessage.success('解锁成功!')
    refreshData()
  }
}
// 表格分页
const getTableFun = async (val) => {
  queryParam.value.pageNo = val.pageNo
  queryParam.value.pageSize = val.pageSize
  let data = { page: val.pageNo, limit: val.pageSize }
  await doSearch(data)
  onClickUnlock()
}
// 查询条件：默认一个空数组
const queryFields = reactive({
  list: []
})

/**
 * 添加一个查询条件
 * 1. 这个方法在进入该页面时校验路由参数并自动执行
 * 2. 在点击查询表单时执行
 */
const addQueryFields = (field, value, queryType, formType) => {
  // let o = new QueryFields()
  queryFields.list.push({ field, value, queryType, formType })
}

/**
 * 添加一个组合条件
 */
const addOperation = (queryFields) => {
  queryFields.forEach((item) => {
    queryParam.value.operations[0].queryFields.push(item)
  })
}

const clearQueryParams = () => {
  queryParam.value.operations = [
    {
      condition: 'must',
      queryFields: []
    }
  ]
  queryFields.list = []
}

// TODO: 把表单构建参数封装起来
// 查询表单结构
const FieldForm = reactive({
  fields: []
})

const entStore = useEntStore()

onMounted(async () => {
  const { query } = route
  let field = '',
    value = ''
  if (query.area) {
    field = 'area'
    value = query.area
  }
  if (query.industry) {
    field = 'industry'
    value = query.industry
  }

  if (query.keyword) {
    field = 'keyword'
    value = query.keyword
  }

  await entStore.setFields({ tempId: query.tempId || 0, field, value })
  FieldForm.fields = entStore.getFields
  searchFn()
})

// 数据集合
const dataList = reactive({
  results: [],
  total: 0
})
// 查询函数
const doSearch = async (page) => {
  if (page) {
    // Mod by PetePower: pageIndex->pageNo
    queryParam.value.pageNo = page.page
    queryParam.value.pageSize = page.limit
  }
  loading.value = true
  let ids
  const { results, total } = await CompanyApi.getCompanyPage(queryParam.value)
  if (results.length) {
    ids = results.map((element) => element.companyInfo.cid)
    const res = await advanceApi.companyGetStatus({ ids: ids })
    dataList.results = mergeValues(results, res)
  } else {
    dataList.results = results
  }
  dataList.total = total
  loading.value = false
}
const mergeValues = (arrayA, objectB) => {
  arrayA.forEach((itemA) => {
    let key = itemA.companyInfo.cid
    if (objectB[key]) {
      Object.assign(itemA.companyInfo, objectB[key])
    }
  })
  return arrayA
}

// 获取地区列表，用于构建选择器
const areaOptions = LocalApi.getAreaList()

// 获取行业列表，用于构建选择器
const industryOptions = LocalApi.getIndustryList()

// TODO: 监听到变化时，要处理这个复杂的查询结构然后去执行查询
watch(FieldForm, (n) => {
  // clearQueryParams()
  // const fields = n.fields
  // fields.forEach((v) => {
  //   if (v.value) {
  //     //是数组
  //     if (isArray(v.value)) {
  //       let list1 = []
  //       let arr = v.value.filter((items) => items != '')
  //       if (arr.length) {
  //         list1.push({ field: v.field, value: arr.join(','), queryType: v.queryType })
  //       }
  //       // 这里冗余了，但是暂时先不修改，后端接口仍需稳定并兼容《高级查询》
  //       if (list1.length > 0) {
  //         addOperation(list1)
  //       }
  //     } else {
  //       addQueryFields(v.field, v.value, v.queryType, v.formType)
  //     }
  //   }
  // })
  // if (queryFields.list.length > 0) {
  //   addOperation(queryFields.list)
  // }
  // doSearch()
})
//详情
const onEntNameClick = async (item, val, index) => {
  //                            显示             cid        锚点?  下标
  companyDetail.value.setDrawer(true, item.companyInfo.cid, val, index)
}
// 刷新
const refreshData = () => {
  doSearch()
}
// 详情刷新
const detailRefreList = (data) => {
  let index = sessionStorage.getItem('companyIndex')
  dataList.results[index].companyInfo.receiveUser = data.receiveUser
  dataList.results[index].companyInfo.received = data.received
}
// 重置
const reset = async () => {
  clearQueryParams()
  FieldForm.fields.forEach((item) => {
    if (item.value && isArray(item.value)) {
      item.value = []
    } else {
      item.value = ''
    }
  })
  doSearch()
}
// 搜索
const searchFn = () => {
  clearQueryParams()
  const fields = FieldForm.fields
  fields.forEach((v) => {
    if (v.value) {
      //是数组
      if (isArray(v.value)) {
        let list1 = []
        let arr = v.value.filter((items) => items != '')
        if (arr.length) {
          list1.push({ field: v.field, value: arr.join(','), queryType: v.queryType })
        }
        // 这里冗余了，但是暂时先不修改，后端接口仍需稳定并兼容《高级查询》
        if (list1.length > 0) {
          addOperation(list1)
        }
      } else {
        addQueryFields(v.field, v.value, v.queryType, v.formType)
      }
    }
  })
  if (queryFields.list.length > 0) {
    addOperation(queryFields.list)
  }
  doSearch()
}
</script>

<style scoped lang="scss">
.page-box {
  padding-top: 10px;
  overflow: hidden;
}
.inner-container {
  width: 1200px;
  margin: 0 auto;
}
// }
</style>
